package com.ohuang.demo.util;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class FileHeaderReader {

    // 读取文件头信息
    public static String getFileHeader(String filePath) {
        FileInputStream is = null;
        String value = null;
        try {
            File f = new File(filePath);
            if (f.exists() && !f.isDirectory()) {
                is = new FileInputStream(f);
                byte[] bytes = new byte[28];
                if (is.read(bytes) != -1) {
                    value = bytesToHexString(bytes);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return value;
    }

    // 将字节数组转换为十六进制字符串表示形式
    private static String bytesToHexString(byte[] src) {
        StringBuilder builder = new StringBuilder();
        if (src == null || src.length <= 0) {
            return null;
        }
        String hv;
        for (byte b : src) {
            // 以十六进制无符号整数形式，
            // 取值范围是 0 到 255 (0xFF)
            // 前面加零填充两位
            hv = Integer.toHexString(b & 0xFF);
            if (hv.length() < 2) {
                builder.append(0);
            }
            builder.append(hv.toUpperCase());
        }
        return builder.toString();
    }


}

